package com.example.miaosha.interceptor;

import com.example.miaosha.constant.Constant;
import com.example.miaosha.util.RedisUtil;
import com.example.miaosha.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 鉴权拦截器
 * @author kangnan
 * @date 2021/5/19 23:11
 **/
public class SysInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        // 当handler处理的是方法时
        if (handler instanceof HandlerMethod) {
            String token = request.getHeader("token");
            if (StringUtil.isEmpty(token)) {
                throw new RuntimeException("签名验证失败，token不存在！");
            } else {
                Object obj = redisUtil.get(Constant.REDIS_TOKEN_PREFIX, token);
                // 验证成功
                if (obj != null) {
                    return true;
                } else {
                    // 验证失败，不存在或过期
                    throw new RuntimeException("签名验证失败！");
                }
            }
        } else {
            // 非方法不拦截
            return true;
        }
    }

}
